package com.yc.rpc.core;

import com.yc.rpc.core.annotation.EnableYcRpc;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;


/**
 * @author 冉野 E-mail:yangtianrui135@163.com
 * @version 创建时间：2021/7/13 4:28 PM
 */
@Component
public class ImportRpcBeanDefinitionRegistry implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {

    ResourceLoader resourceLoader;

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry, BeanNameGenerator importBeanNameGenerator) {
        YcRpcClasssPathBeanDefinitionScanner scanner = new YcRpcClasssPathBeanDefinitionScanner(registry, false);
        scanner.setResourceLoader(resourceLoader);
        scanner.registerFilters();
        Set<BeanDefinitionHolder> beanDefinitionHolders = scanner.doScan(getBasePackages(importingClassMetadata));

        GenericBeanDefinition definition;


        for (BeanDefinitionHolder holder : beanDefinitionHolders) {
            definition = (GenericBeanDefinition) holder.getBeanDefinition();
            String beanClassName = definition.getBeanClassName();

//            definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);

            try {
                definition.getPropertyValues().addPropertyValue("type", Class.forName(definition.getBeanClassName()));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }


            definition.setBeanClass(YcRpcFactoryBean.class);


        }

    }

   private String[] getBasePackages(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> attrbitues = importingClassMetadata.getAnnotationAttributes(EnableYcRpc.class.getCanonicalName());
        return (String[]) attrbitues.get("basePackages");

    }

}
